#include "ListenerPlugin.h"

#include <QTimer>
#include <iostream>
#include <qDebug>

#include "./Base/data.h"
#include "service/event/ctkEventConstants.h"
#pragma execution_character_set("utf-8")  // 界面界面中文乱码问题
Q_DECLARE_METATYPE(data);
ListenerPlugin::ListenerPlugin(ctkPluginContext* context)
    : ctk_plugin_context_(context) {
  listener_plugin_widget_ = new ListenerPluginWidget();

  // 注册监听信号
  ctkDictionary ctk_dic;
  ctk_dic.insert(ctkEventConstants::EVENT_TOPIC, "EventListenerPlugin");
  ctk_plugin_context_->registerService<ctkEventHandler>(this, ctk_dic);

  ctk_dic.insert(ctkEventConstants::EVENT_TOPIC, "send");
  ctk_plugin_context_->registerService<ctkEventHandler>(this, ctk_dic);

  QTimer* timer = new QTimer(this);
  connect(timer, &QTimer::timeout, [&]() {
    qDebug() << "timer timeout";
    data datas = {1, 2, 3};
    QString topic = "mesg";
    ctkDictionary dict;

    dict.insert(topic, QVariant::fromValue(datas));
    SendEvent(topic, dict);
  });
  // timer->start(1000);
}

ListenerPlugin::~ListenerPlugin() {}

QWidget* ListenerPlugin::CreateWidget() { return listener_plugin_widget_; }

void ListenerPlugin::InitWidget() {}

QString ListenerPlugin::GetDockObjectName() {
  return QString("ListenerPluginkWidget");
}

QString ListenerPlugin::GetDockWidgetName() { return QString(); }

Qt::DockWidgetArea ListenerPlugin::GetDockWidgetArea() {
  return Qt::DockWidgetArea();
}

QDockWidget::DockWidgetFeatures ListenerPlugin::GetDockFeatures() {
  return QDockWidget::DockWidgetFeatures();
}

void ListenerPlugin::handleEvent(const ctkEvent& event) {  // 接收监听事件接口
  if (event.getTopic() == "mesg") {
    QVariant data1 = event.getProperty(event.getTopic());
    data mesg = data1.value<data>();
    qDebug() << mesg.x << mesg.y << mesg.z;
  }
}

void ListenerPlugin::SendEvent(const QString topic, const ctkDictionary& obj) {
  ctkServiceReference ref;
  ctkEventAdmin* eventAdmin{nullptr};
  ref = ctk_plugin_context_->getServiceReference<ctkEventAdmin>();
  if (ref) {
    eventAdmin = ctk_plugin_context_->getService<ctkEventAdmin>(ref);
    ctk_plugin_context_->ungetService(ref);
  }

  if (eventAdmin) {
    eventAdmin->postEvent(ctkEvent(topic, obj));
  }
}
